<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="pattern_name" label="图案名称" required>
        <uni-easyinput placeholder="图案名称" v-model="formData.pattern_name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="pattern_name_en" label="图案英文名称">
        <uni-easyinput placeholder="图案英文名称" v-model="formData.pattern_name_en"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="pattern_file" label="图案文件" required>
        <uni-file-picker 
          ref="patternFilePicker"
          v-model="patternFileList"
          file-mediatype="all"
          :auto-upload="true"
          limit="1"
          @select="selectPatternFile"
          @success="successPatternFile"
          @fail="failUpload"
        ></uni-file-picker>
        <text class="file-path" v-if="formData.pattern_file">已上传路径: {{formData.pattern_file}}</text>
      </uni-forms-item>
      <uni-forms-item name="preview_image" label="预览图片">
        <uni-file-picker 
          ref="previewImagePicker"
          v-model="previewImageList"
          file-mediatype="image"
          :auto-upload="true"
          limit="1"
          @select="selectPreviewImage"
          @success="successPreviewImage"
          @fail="failUpload"
        ></uni-file-picker>
        <text class="file-path" v-if="formData.preview_image">已上传路径: {{formData.preview_image}}</text>
      </uni-forms-item>
      <uni-forms-item name="category" label="图案分类">
        <uni-data-checkbox v-model="formData.category" :localdata="formOptions.category_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="tags" label="标签列表">
        <uni-data-checkbox :multiple="true" v-model="formData.tags"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="duration" label="播放时长（秒）">
        <uni-easyinput placeholder="播放时长（秒）" type="number" v-model="formData.duration"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="difficulty" label="复杂度等级">
        <uni-data-checkbox v-model="formData.difficulty" :localdata="formOptions.difficulty_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="download_count" label="下载次数">
        <uni-easyinput placeholder="下载次数" type="number" v-model="formData.download_count"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="favorite_count" label="收藏次数">
        <uni-easyinput placeholder="收藏次数" type="number" v-model="formData.favorite_count"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="designer" label="设计师">
        <uni-easyinput placeholder="设计师" v-model="formData.designer"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="图案描述">
        <uni-easyinput placeholder="图案描述" v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="is_featured" label="是否为精选图案">
        <switch @change="binddata('is_featured', $event.detail.value)" :checked="formData.is_featured"></switch>
      </uni-forms-item>
      <uni-forms-item name="is_premium" label="是否为付费图案">
        <switch @change="binddata('is_premium', $event.detail.value)" :checked="formData.is_premium"></switch>
      </uni-forms-item>
      <uni-forms-item name="compatible_devices" label="兼容设备类型">
        <uni-data-checkbox :multiple="true" v-model="formData.compatible_devices"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="status" label="状态：0-草稿，1-发布，2-下架">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/sh_pattern.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'sh_pattern';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "pattern_name": "",
        "pattern_name_en": "",
        "pattern_file": "",
        "preview_image": "",
        "category": "",
        "tags": [],
        "duration": null,
        "difficulty": null,
        "download_count": null,
        "favorite_count": null,
        "designer": "",
        "description": "",
        "is_featured": null,
        "is_premium": null,
        "compatible_devices": [],
        "status": null
      }
      return {
        formData,
        patternFileList: [],
        previewImageList: [],
        formOptions: {
          "category_localdata": [
            {
              "value": "nature",
              "text": "nature"
            },
            {
              "value": "animal",
              "text": "animal"
            },
            {
              "value": "abstract",
              "text": "abstract"
            },
            {
              "value": "geometry",
              "text": "geometry"
            },
            {
              "value": "art",
              "text": "art"
            },
            {
              "value": "other",
              "text": "other"
            }
          ],
          "difficulty_localdata": [
            {
              "value": 1,
              "text": 1
            },
            {
              "value": 2,
              "text": 2
            },
            {
              "value": 3,
              "text": 3
            },
            {
              "value": 4,
              "text": 4
            },
            {
              "value": 5,
              "text": 5
            }
          ],
          "status_localdata": [
            {
              "value": 0,
              "text": 0
            },
            {
              "value": 1,
              "text": 1
            },
            {
              "value": 2,
              "text": 2
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },
      
      /**
       * 图案文件选择回调
       */
      selectPatternFile(e) {
        console.log('选择图案文件:', e)
      },
      
      /**
       * 图案文件上传成功回调
       */
      successPatternFile(e) {
        console.log('图案文件上传成功', e)
        if (e.tempFilePaths && e.tempFilePaths.length > 0) {
          // 如果有临时路径，取第一个
          this.formData.pattern_file = e.tempFilePaths[0]
        } else if (e.tempFiles && e.tempFiles.length > 0 && e.tempFiles[0].url) {
          // 否则取上传后的url
          this.formData.pattern_file = e.tempFiles[0].url
        }
      },
      
      /**
       * 预览图片选择回调
       */
      selectPreviewImage(e) {
        console.log('选择预览图片:', e)
      },
      
      /**
       * 预览图片上传成功回调
       */
      successPreviewImage(e) {
        console.log('预览图片上传成功', e)
        if (e.tempFilePaths && e.tempFilePaths.length > 0) {
          this.formData.preview_image = e.tempFilePaths[0]
        } else if (e.tempFiles && e.tempFiles.length > 0 && e.tempFiles[0].url) {
          this.formData.preview_image = e.tempFiles[0].url
        }
      },
      
      /**
       * 上传失败回调
       */
      failUpload(e) {
        console.error('文件上传失败', e)
        uni.showModal({
          content: `文件上传失败: ${e.errMsg || '未知错误'}`,
          showCancel: false
        })
      },
      
      /**
       * 绑定开关类型数据
       */
      binddata(key, value) {
        this.formData[key] = value
      }
    }
  }
</script>

<style>
.uni-container {
  padding: 15px;
}
.file-path {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
  display: block;
}
</style>
